//封装一个axios的对象并导出，对象名为‘request’

import axios from 'axios'
import { Loading, Message } from 'element-ui';

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL:'/dev-api',
  timeout: 5000
})

const loading = {
  loadingInstance: null,
  // 打开加载
  open: function () {
    console.log('加载中', this.loadingInstance)
    // 为了避免创建过多的实例，如果实例为空，则创建
    if (this.loadingInstance === null) {
      console.log("创建加载实例。。。")
      this.loadingInstance = Loading.service({
        text: '拼命加载中',
        target: '.main',
        background: "rgba(0, 0, 0, 0.5)"
      })
    }
  },
  // 关闭加载
  close: function () {
    if (this.loadingInstance !== null) {
      this.loadingInstance.close()
      console.log("结束加载")
    }
    // 重新赋值为空
    this.loadingInstance = null
  }
}

// request.get('/db.json').then(response =>{
//     console.log(response.data)
// })

//拦截器
// 请求拦截器
request.interceptors.request.use(function (config) {
  loading.open()
  return config;
}, function (error) {
  loading.close()
  return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(function (response) {
  loading.close()
  const resp = response.data
  if (resp.code !== 2000) {
    Message({
      message: resp.message || "系统异常",
      type: 'warning',
      duration: 5 * 1000
    })
  }

  return response;

}, function (error) {
  loading.close()
  console.log('response error', error.response.status)
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error);
});

export default request